<?php #title=Банеры;


if(!empty($_GET['action']) && $_GET['action']=='delete')
{
    $conn->query('DELETE FROM banner WHERE id = '.$_GET['id']);
    successRedirect(array('url'=>'?p=baner'));
}


$date_stop = date('Y-m-d', time()+(60*60*24*31*12*10));

$baner = (object)array(
                        'id'=>false,
                        'name'=>'',
                        'file_name'=>array(),
                        'date_stop'=>$date_stop,
                        'templ'=>'',
                        'pages'=>'',
                        'position'=>'',
                        'link'=>'',
                        'brand_id'=>''
                        );

if(!empty($_POST))
{
    if(!empty($_FILES['file_name']))
    {
        $files = array();
        $links = array();
        $dir = $_SERVER['DOCUMENT_ROOT'].'/inc/images/banner/';
        foreach ($_FILES['file_name']['name'] as $key => $file_name) {
            $tmp = $_FILES['file_name']['tmp_name'][$key];
            if(is_uploaded_file($tmp))
            {
                move_uploaded_file($tmp,$dir.$file_name);
                $files[] = $file_name;
                $links[$key] = $_POST['link'][$key];
            }
        }

        if(!empty($_POST['file_name']))
        {
           foreach ($_POST['file_name'] as $key => $value) {
                if(!isset($files[$key]))
                    $files[$key] = $value;
                $links[$key] = $_POST['link'][$key];
            }
        }

        $file = implode(',', $files);
        $link = implode(',', $links);

        $file_name = ' file_name="'.$file.'",';
        $link = 'link="'.$link.'",';
    }

    $where = '';
    $method = 'INSERT INTO';

    if(!empty($_GET['id']))
    {
        $where=' WHERE id = '.$_GET['id'];
        $method = 'UPDATE ';
    }

      $baner_id = $conn->query($method.' banner SET
                    name="'.$_POST['name'].'",
                   '.$file_name.'
                    date_stop="'.$_POST['date_stop'].'",
                    position="'.$_POST['position'].'",
                    brand_id="'.$_POST['brand_id'].'",
                    '.$link.'
                    templ="'.$_POST['templ'].'"'.$where,1);



      if(isset($_POST['edited']))
      {

          if(!empty($_GET['id'])){
             $baner_id = $_GET['id'];
             $conn->query('DELETE FROM baner_relation WHERE baner_id='.$baner_id);
          }

          if(!empty($_POST['pages']))
          {
             foreach($_POST['pages'] as $page_id)
             {
                $conn->query('INSERT INTO baner_relation SET page_id='.$page_id.',baner_id='.$baner_id);
             }
          }
      }

    successRedirect(array('url'=>'?p=baner'));
}


$selected_files = array();

$file_list = '';

if(!empty($_GET['id']))
{
    $conn->query('SELECT * FROM banner WHERE id ='.$_GET['id']);
    if($conn->rowCount())
    {
        $baner=$conn->fetch();
        $files = explode(',',$baner->file_name);
        $links = explode(',',$baner->link);
        $key = false;
        foreach ($files as $key => $value) {
            $file_list .= '
            <li class="_prot">
                <span>Ссылка</span> <input type="text" name="link[]" value="'.$links[$key].'"/>
                <input type="hidden" name="file_name[]" value="'.$value.'"/>
                <label>Файл (желаете поменять?)</label><input type="file" name="file_name[]"/>
                <div class="_delete"><span>X</span></div>
            </li>
            ';
        }
    }
}

$baner_file = '
    <div class="_list_file">
        <ul>
            '.$file_list.'
            <li class="_prot">
                <span>Ссылка</span> <input type="text" name="link[]"/>
                <label>Файл</label><input type="file" name="file_name[]"/>
            </li>

        </ul>
        <button class="_add_file">добавить</button>
    </div>
';

$templ = array(
               ''=>'Выбор категории',
                '_main'=>'Главная',
                'category'=>'Категория товаров',
                'sub_category'=>'Подкатегория товаров',
                'product'=>'Карточка товаров'
);

$pages = array();

$sql = 'SELECT id,title,parents FROM pages WHERE templ in ("category") ORDER BY title';

if(!empty($_GET['id']))
    $sql = 'SELECT id,title,parents,br.page_id as br_page_id FROM pages p
             LEFT JOIN baner_relation br on br.page_id = p.id and br.baner_id="'.$_GET['id'].'"
             WHERE templ in ("category") ORDER BY title';


$conn->query($sql);
$select_page = '';
if($conn->rowCount())
{
  $select_page .= '<ul>';
  while( $row = $conn->fetch())
  {
    $pages[$row->id] = $row->title;
    $field_id = 'select_page_'.$row->id;
    $parents = $row->parents.'#'.$row->id.'#';

    $checked = '';

    if(property_exists($row,'br_page_id'))
        if($row->br_page_id > 0)
           $checked = 'checked="checked"';

    $select_page .= '
    <li _parents="'.$parents.'">
      <input type="checkbox" '.$checked.' name="pages[]" value="'.$row->id.'">
      <label><span>'.$row->title.'</span></label>
    </li>';
  }
  $select_page .= '</ul>';
}

$brand_list = array('Выбор');
$conn->query('SELECT * FROM store_product_brand ORDER BY name',0,'brand');
while($row = $conn->fetch('brand'))
    $brand_list[$row->id] = $row->name;

$select_templ = $load->block('form_element',array('type'=>'select','name'=>'templ','values'=>$templ,'val'=>$baner->templ));
$select_brand = $load->block('form_element',array('type'=>'select','name'=>'brand_id','values'=>$brand_list,'val'=>$baner->brand_id));

$date_stop = $load->block('form_element',array('type'=>'date','name'=>'date_stop','val'=>$baner->date_stop));

$select_position = $load->block('form_element',array('type'=>'select','name'=>'position','values'=>array(''=>'Выбор','top'=>'Сверху','bot'=>'Снизу'),'val'=>$baner->position));

$submit = $load->block('buttons',array('text'=>!empty($_GET['id'])?'сохранить':'добавить','type'=>'submit'));



$baner_id = !empty($_GET['id']) ? $_GET['id'] : 0;

$form=<<<HTML
            <div class="fields-editor form product_edit">
                <form action="" method="post" enctype="multipart/form-data">
                <input type="hidden" name="baner_id" value="$baner_id">
                <div class="title"><span>Форма</span></div>
                <div class="data">
                    <div class="left">
                        <div class="field">
                            <div class="desc"><span>Название:</span></div><input type="text" class="text " name="name" value="{$baner->name}">
                        </div>
                        <div class="field">
                            <div class="desc"><span>Дата окончания показа</span></div>
                            $date_stop
                        </div>
                        <div class="field">
                         <div class="desc"><span>Банеры</span></div>
                        $baner_file
                        </div>
                    </div>
                    <div class="right">
                        <div class="field">
                            <div class="desc"><span>Выбор категории:</span></div>
                            $select_templ
                        </div>
                        <div class="field">
                            <div class="desc"><span>Выбор позиции:</span></div>
                            $select_position
                        </div>
                        <div class="field">
                            <div class="desc"><span>Выбор производителя:</span></div>
                            $select_brand
                        </div>
                        <div class="field select_page">
                            <div class="desc"><span>Выбор страниц:</span> <input type="checkbox" name="edited" disabled="disabled"> (ред.)</div>
                            <div class="select_page_design">$select_page</div>
                        </div>
                    </div>
                    <div class="field">
                                $submit
                        </div>
                <div class="clear"></div>
                </div>
               </form>

            </div>
HTML;


$view->gText.='<h3>Банеры</h3>';
if(!empty($_GET['action'])){
    if($_GET['action']=='add' || $_GET['action']=='update')
        $view->gText.='<a href="?p=baner">вернуться назад</a>'.$form;


}else
        $view->gText.='<a href="?p=baner&action=add">добавить</a>';
$view->gText.=$load->block('table_editor',array(
    'control_name'=>'Быстрое редактирование',
    'can_edit'=>true,
    'dev'=>true,
    'select'=>array('from'=>'banner'),
    'fields'=>array(
        'id'=>array('sys_id'=>true,'title'=>'ID','to_edit'=>false),
        'name'=>array('title'=>'Название'),
        array('link'=>"<a href='?p=baner&action=update&id=#id#'>редактировать</a>",'to_edit'=>0),
        array('link'=>"<a href='?p=baner&action=delete&id=#id#'>удалить</a>",'to_edit'=>0)
        ),
    'link_replaces'=>array('parents')
));

$view->js_on_load[]='

$("._list_file ._delete").live("click",function(){
    $(this).parent().remove();
    return false;
});

$("._list_file ._add_file").live("click",function(){
    elem = $("._list_file");
    var field = elem.find("._prot:first").clone().removeClass("_prot");
    elem.find("ul").append(field);
    return false;
});

$(".select_page label").live("click",function(){

  element = $(this).parent();
  checkbox = element.children("[type=checkbox]").attr("checked");
  if(element.is("._empty"))
   return false;
  if(!element.children("ul").html())
   {
      var parents  = element.attr("_parents");
     if(parents.length>0)
     {
      var params = {parents:parents,checked:checkbox};
      var baner_id = $("[name=baner_id]").val();
      if(baner_id > 0)
         params.baner_id = baner_id;
      $.post("?ajax=baner",params,function(html){
         if(html.length>0)
         {
            element.append(html);
            element.children("ul").slideDown();
         }
         else
         {
            element.addClass("_empty");
         }
      });
     }
   }
   else
   {
      if(!element.children("ul").is(":hidden"))
      {
         element.children("ul").slideUp();
      }
      else
      {
         console.log("pajaluysta");
         element.children("ul").slideDown();
      }
   }
});

$(".select_page [type=checkbox]").live("click",function(){
    $("[name=edited]").removeAttr("disabled").attr("checked","checked");
   element = $(this);
   if(element.attr("checked"))
      checkAllChildren(element.parent(),true);
   else
      checkAllChildren(element.parent(),false);
});

function checkAllChildren(element,check)
{
   console.log();
   element.find("[type=checkbox]").each(function(){
      if(check)
         $(this).attr("checked",true);
      else
         $(this).removeAttr("checked");
   });
}
';

$view->gText .= '<style>

._list_file li{
    position:relative;
}

._list_file ._delete{
    position: absolute;
    right: 0;
    top: 0;
    color: rgb(255, 255, 255);
    font-weight: bold;
    background: red;
    border-radius: 50px;
    width: 16px;
    height: 16px;
    text-align: center;
    line-height: 16px;
    font-family: tahoma;
}

._list_file ._delete:hover{
    cursor:pointer;
}

.product_edit .left{
    float:left;
    width:500px;
}

.product_edit .right{
    float:left;
    width:560px;
}

.select_page_design{
border-radius: 20px;
background: #ddd;
padding: 10px 0px;
margin: 13px 20px 0 20px;
}


.select_page_design ul{
   list-style:none;
   margin-left:20px;
}
</style>';

